package server.config.shiro;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import server.dao.FrmRoleDao;
import server.dao.RolePermissionsDao;
import server.dao.UsersDao;
import server.model.entity.FrmRole;
import server.model.entity.Permissions;
import server.model.entity.RolePermissions;
import server.model.entity.Users;
import server.tool.tool.EDcrypionUtils;

import java.io.UnsupportedEncodingException;
import java.util.*;

public class UserRealm extends AuthorizingRealm {
    private Logger logger = LoggerFactory.getLogger(AuthorizingRealm.class);

    @Autowired
    private UsersDao usersDao;

    @Autowired
    private FrmRoleDao frmRoleDao;

    @Autowired
    private RolePermissionsDao rolePermissionsDao;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Users fspUser = (Users) principalCollection.getPrimaryPrincipal();
        Collection<String> roles = new LinkedHashSet<>();
        Set<String> permissions = new LinkedHashSet<>();
        FrmRole userRoles = fspUser.getRole();
        roles.add(userRoles.getId());
        List<RolePermissions> rolePermissions = rolePermissionsDao.findByRole(userRoles);
        //根据角色找权限
        List<Permissions> fspRolePermissionsList = new LinkedList<>();
        for (RolePermissions roper : rolePermissions) {
            fspRolePermissionsList.add(roper.getPermissions());
        }
        for (Permissions fspRolePermissions : fspRolePermissionsList) {
            permissions.add(fspRolePermissions.getCode());
        }
        authorizationInfo.addRoles(roles);
        authorizationInfo.addStringPermissions(permissions);
        return authorizationInfo;
    }

    //登录
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1，获得前端传值
        String username = (String) authenticationToken.getPrincipal();
        Users user = usersDao.findByMobile(username);
        if (user == null) {
            user = usersDao.findByUserName(username);
        }
        if (user == null || user.getStatus() == false) {
            user = null;
        }
        if (user == null) {
            //没找到帐号
            throw new UnknownAccountException();
        }
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashIterations(10);
        matcher.setHashAlgorithmName("md5");
        this.setCredentialsMatcher(matcher);
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), "");
        //盐
        authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(EDcrypionUtils.key));
        //将用户信息放入session中
        SecurityUtils.getSubject().getSession().setTimeout(-1000l);
        user.setPassword("");
        SecurityUtils.getSubject().getSession().setAttribute("Users", user);
        return authenticationInfo;
    }

    //加密
    public static void main(String[] args) throws UnsupportedEncodingException {
        System.out.println(EDcrypionUtils.shiroPassword("123456"));
    }

}
